package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Used to start the Server
 *
 * @author Gruppe 95
 *
 */
public class ServerMain {
    private static final String COMM_CLOSE = "!close";
    private static final String COMM_RECONNECT = "!reconnect";
    private static final String COMM_EXIT = "!exit";


    /*
     * AuctionServer main method.
     * Needs 3 arguments:
     * TCP-Port, AnalyticsServer-binding-name, BillingServer-binding-name.
     */
    public static void main(String[] args) {
        Server server;

//        if (args.length != 5) 
//        {
//            System.out.println("Usage:");
//            System.out.println("java Server <tcpPort> <analyticsserver-binding> <billingserver-binding> <servers-privatekey-file> <client-keyfile-dir>");
//        }
        try {
            //for teststart without arguments
            if (args.length == 0) {
                System.out.println("start auction-server without arguments");
                server = new Server("13240", "Analytics", "Billing", "keys/auction-server.pem", "keys/");
            } else {
                server = new Server(args[0], args[1], args[2], args[3], args[4]);
            }


            server.start();
            Thread serverThread = new Thread(server);
            serverThread.start();
            try {
                InputStreamReader inputStream = new InputStreamReader(System.in);
                BufferedReader brStdIn = new BufferedReader(inputStream);
                String strLine;
                while ((strLine = brStdIn.readLine()) != null) {
                    if (strLine.contentEquals(COMM_EXIT)) {
                        System.out.println("Exit-command entered, Server Thread will be stopped...");
                        server.stop();
                        brStdIn.close();
                        inputStream.close();
                        break;
                    } else if (strLine.contentEquals(COMM_CLOSE)) {
                        server.stop();
                    } else if (strLine.contentEquals(COMM_RECONNECT)) {
                        server.setInterrupted(false);
                        server.setStopped(false);
                        serverThread = new Thread(server);
                        serverThread.start();
                    }
                }
            } catch (IOException e) {
                System.out.println("IOException occured while listening on stdin " + e.getMessage());
            }
        } catch (NumberFormatException ex) {
            System.out.println("tcpPort has to be numeric!");
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}